package com.itany.shop.filter;

import com.itany.shop.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author 黄衡熙
 * @version 1.0
 */
@WebFilter("/*")
public class CheckLoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取访问的请求
        String path = request.getServletPath();
        // 判断当前请求是否是注册、登录、主页相关的请求
        // 如果是这些请求,则直接放行,不做校验
        if(path.endsWith(".user") || "/jsp/login.jsp".equals(path) || "/jsp/register.jsp".equals(path) || "/jsp/main.jsp".equals(path) || "/index.jsp".equals(path) || "/findAll.product".equals(path) || "/showCode".equals(path)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        // 如果不是登录、注册、主页相关的请求,则需要用户登录后才可以访问
        // 当用户登录成功之后,会将用户信息保存到session
        // 获取session中的用户信息
        // 如果获取到了,则说明用户已经登录
        // 如果没有获取到,则说明用户尚未登录
        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            // 如果尚未登录,跳转到登录页面,给出提示消息
            request.setAttribute("loginMsg","您尚未登录,请先登录后再访问对应请求");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            return;
        }
        // 如果用户已经登录了,则直接放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
